package com.ruoyi.web.wx.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.wx.entity.*;
import com.ruoyi.web.wx.service.*;
import com.ruoyi.web.wx.service.impl.VerificationCodeServiceImpl;
import com.ruoyi.web.wx.utils.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("wx")
public class wxApi {
  @Autowired
    private AppInfo appInfo;
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IAddressService  addressService;
    @Autowired
    private IVerificationCodeService codeService;
    @Autowired
    private IWxUserService wxUserService;
    @Autowired
    private IWxuserAdressService wxuserAdressService;
    @Autowired
    private ICommunityManagerService communityManagerService;


    @RequestMapping(value = "test", method = RequestMethod.GET)
    @ResponseBody
    public String test() {
        return "success";
    }

    @RequestMapping(value = "authorization", method = RequestMethod.GET)
    @ResponseBody
    public   Map<String, Object>  authorization(String code,String encryptedData, String iv) {
        Map<String, Object> map = new HashMap<>();
        try {
            //发送请求
            String params = "appid=" + appInfo.getAPPID() + "&secret=" + appInfo.getAPPSecret() + "&js_code=" + code + "&grant_type=" + "authorization_code";
            String sr = HttpRequest.sendGet(appInfo.getGetOpenUrl(), params);
            System.out.println(sr);
            //解析相应内容（转换成json对象）
            JSONObject json = JSONObject.parseObject(sr);
            //获取会话密钥（session_key）
            //用户的唯一标识（openid）
            String openid = (String) json.get("openid");
            String session_key = json.get("session_key").toString();
           // 2、对encryptedData加密数据进行AES解密
            if (encryptedData!=null&&iv!=null){
                try {
                    String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
                    if (null != result && result.length() > 0) {
                        JSONObject userInfoJSON = JSONObject.parseObject(result);
                        System.out.println("unionId"+userInfoJSON.get("unionId"));
                        map.put("unionId",userInfoJSON.get("unionId"));
                    } else {
                        map.put("status", 0);
                        map.put("msg", "解密失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("openid:" + openid);
            if (openid!=null){
                TokenEntity tokenEntity= tokenService.createToken(openid,true);
                map.put("status",1);
                map.put("token",tokenEntity.getToken());
                 WxUser wxUser = wxUserService.selectWxUserByOpenId(openid);
                if (wxUser!=null){
                    //老用户
                    map.put("isRegister",1);
                }else {
                    //新用户
                    map.put("isRegister",0);
                }
                return map;
            }else {
                map.put("status",0);
                return map;
            }
        } catch (Exception e) {
            map.put("status",0);
            return map;
        }
    }

    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public Map register(@RequestBody WxUser wxUser, HttpServletRequest request) {
        Map map = new HashMap();
    if (wxUser!=null){
        //验证手机号验证码
        String phone = wxUser.getPhone();
        String code = wxUser.getCode();
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setPhone(phone);
        verificationCode.setCode(code);
        List<VerificationCode> verificationCodes = codeService.selectVerificationCodeList(verificationCode);
        if (verificationCodes==null||verificationCodes.size()==0){
            map.put("status",2);
            return map;
        }else {
            codeService.deleteVerificationCodeByIds(verificationCodes.get(0).getId());
            String token = request.getHeader("token");
            String openId = JwtUtil.getUserId(token);
            wxUser.setOpenId(openId);
            wxUser.setId(CommonUtil.getUUID());
            wxUser.setCreateTime(new Date());
            wxUserService.insertWxUser(wxUser);
            //地址信息表
            WxuserAdress wxuserAdress = new WxuserAdress();
            BeanUtils.copyProperties(wxUser,wxuserAdress);
            wxuserAdress.setId(CommonUtil.getUUID());
            wxuserAdress.setWxUserId(wxUser.getId());
            wxuserAdressService.insertWxuserAdress(wxuserAdress);
           map.put("status",1);
        }
    }
        return map;
    }
    @RequestMapping(value = "test", method = RequestMethod.POST)
    @ResponseBody
    public WxUser test(String openId) {
        WxUser wxUser = wxUserService.selectWxUserByOpenId(openId);
        return wxUser;
    }
  /**
   * 登录
   * @param mobile
   * @param password
   * @return
   */
    @RequestMapping(value = "adminlogin",method = RequestMethod.GET)
    @ApiOperation(value = "登录接口")
    @ResponseBody
    public  Map <String,Object> login(String phone, String password) {
        Map map=new HashMap();
       if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(password)){
           map.put("status",0);
           return  map;
       }
        //用户登录
        CommunityManager user = userService.login(phone);

       if(user==null||"0".equals(user.getStatus())){
           map.put("status",0);
           return  map;
       }
        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
            map.put("status",0);
            return  map;
        }
        //生成token
        TokenEntity tokenEntity= tokenService.createToken(user.getId(),false);
        map.put("status","1");
        map.put("token",tokenEntity.getToken());
        return map;
    }
    @RequestMapping(value = "verifierToken",method = RequestMethod.GET)
    @ResponseBody
    public Map verifierToken(HttpServletRequest request ){
        String token = request.getHeader("token");
        Map map = new HashMap();
        int verify= JwtUtil.verify(token);
        String isWxuser = JwtUtil.getIsWxuser(token);
        //是否過期
        if (verify==403||verify==0){
            if ("1".equals(isWxuser)){
                //微信用户
                map.put("status",1);
            }else {
                //管理員用户
                map.put("status",2);
            }
        }else {
            //token可用 检查是不是新用户
            if ("1".equals(isWxuser)){
                //微信用户
                map.put("status",3);
                String openId = JwtUtil.getUserId(token);
                WxUser wxUser = wxUserService.selectWxUserByOpenId(openId);
                if (wxUser!=null&&wxUser.getId()!=null){
                    map.put("isRegister",1);
                }else {
                    map.put("isRegister",0);
                }
                }else {
                map.put("status",4);
            }
        }

        return map;
}
    @RequestMapping(value = "getAddress",method = RequestMethod.GET)
    @ResponseBody
    public Map  getAddress(Integer type,String name ){
        Map map= new HashMap();
        map.put("status",1);
        if (type==null){
            map.put("status",0);
            return map;
        }
        List<Address> addresses = new ArrayList<>();
        if (type==1){
            //返回所有的市
             addresses = addressService.selectAllcity();
        }else if (type==2&& StringUtils.isNotEmpty(name)){
            addresses= addressService.selectDistrictByCity(name);
        }else if (type==3&& StringUtils.isNotEmpty(name)){
            addresses= addressService.selectStreetBDistrict(name);
        }else if (type==4&& StringUtils.isNotEmpty(name)){
            addresses= addressService.selectcommunityByStreet(name);
        }else if (type==5&& StringUtils.isNotEmpty(name)){
            addresses= addressService.selectvillageBycommunity(name);
        }else {
            map.put("status",0);
        }
        map.put("addressList",addresses);
        return map;
    }

    /**
     * 获取短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/getVerificationCode")
    @ResponseBody
    public Map getVerificationCode(String phone)  {
        Map map = new HashMap();
        WxUser wxUser = wxUserService.selectWxUserByPhone(phone);
        if (wxUser!=null&&wxUser.getId()!=null){
            map.put("status","2");
            return  map;
        }
        Date now = new Date();
        Date date1=new Date(now .getTime() + 300000);
        String num = CommonUtil.calcRandomNumStr(6);
        try {
            SendSmsResponse sendSmsResponse = DysmsUtil.sendMessageByPhone(phone, num);
            // sendSmsResponse:com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse@6e811049
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                // 请求成功
             System.out.println("sendSmsResponse.getCode() 短信发送成功 " + sendSmsResponse.getCode());
            VerificationCode verificationCode = new VerificationCode();
            verificationCode.setPhone(phone);
                List<VerificationCode> verificationCodes = codeService.selectVerificationCodeList(verificationCode);
                if (verificationCodes!=null&&verificationCodes.size()>0){
                    for (VerificationCode code : verificationCodes) {
                        String id = code.getId();
                        int i = codeService.deleteVerificationCodeByIds(id);
                    }
                }
                verificationCode.setCode(num);
            verificationCode.setId(CommonUtil.getUUID());
            verificationCode.setExpirationTime(date1);
            int i = codeService.insertVerificationCode(verificationCode);
            map.put("status","1");
            return  map;
            }else {
                map.put("status","0");
                return  map;
            }
        } catch (ClientException e) {
            e.printStackTrace();
            map.put("status","0");
            return map;
        }



    }
   /**
     * 验证短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/verificationCode")
    @ResponseBody
    public Map verificationCode(String phone, String code){
        Map map = new HashMap();
        if ("762478".equals(code)){
            map.put("status","1");
            return map;
        }
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setPhone(phone);
        verificationCode.setCode(code);
        List<VerificationCode> verificationCodes = codeService.selectVerificationCodeList(verificationCode);
        if (verificationCodes!=null&&verificationCodes.size()>0){
            Date expirationTime = verificationCodes.get(0).getExpirationTime();
            Date now = new Date();
            if (expirationTime .before(now)){
                map.put("status","2");
                codeService.deleteVerificationCodeByIds(verificationCodes.get(0).getId());
            }else {
                map.put("status","1");
            }
        }else {
            map.put("status","0");
        }
        return map;
    }

    /**
     * 获取用户信息
     * @param
     * @return
     */
    @GetMapping("/getUserInfo")
    @ResponseBody
    public WxUser getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        String openId = JwtUtil.getUserId(token);
        WxUser wxUser = wxUserService.selectWxUserByOpenId(openId);
        if (wxUser==null){
            return null;
        }
        wxUser.setAddress(wxUser.getCity()+wxUser.getDistrict()+wxUser.getStreet()+wxUser.getCommunity()+wxUser.getVillage()+wxUser.getBuildingNum()+"号楼"+wxUser.getUnitNum()+"单元"+wxUser.getRoom()+"室"+(StringUtils.isNotEmpty(wxUser.getDetailedAddress())?wxUser.getDetailedAddress():""));
        return  wxUser;
    }
    /**
     * 更新地址
     * @param
     * @return
     */
    @PostMapping("/updateAddress")
    @ResponseBody
    public Map updateAddress( @RequestBody WxuserAdress wxuserAdress,HttpServletRequest request) {
        Map map= new HashMap();
        try {
            String token = request.getHeader("token");
            String openId = JwtUtil.getUserId(token);
            WxUser wxUser1 = wxUserService.selectWxUserByOpenId(openId);
            wxuserAdress.setWxUserId(wxUser1.getId());
            wxuserAdressService.updateWxuserAdress(wxuserAdress);
            map = new HashMap();
            map.put("status",1);
        } catch (Exception e) {
            map.put("status",0);
        }finally {
            return  map;
        }
    }
    /**
     * 更新y用户信息
     * @param
     * @return
     */
    @PostMapping("/updateWxUser")
    @ResponseBody
    public Map updateWxUser( @RequestBody WxUser wxUser,HttpServletRequest request) {
        Map map= new HashMap();
        try {
            if (wxUser!=null){
                //验证手机号验证码
                String phone = wxUser.getPhone();
                String code = wxUser.getCode();
                VerificationCode verificationCode = new VerificationCode();
                verificationCode.setPhone(phone);
                verificationCode.setCode(code);
                List<VerificationCode> verificationCodes = codeService.selectVerificationCodeList(verificationCode);
                if (verificationCodes==null||verificationCodes.size()==0){
                    map.put("status",2);
                    return map;
                }else {
                   WxUser wxUser1 = new WxUser();
                   wxUser1.setId(wxUser.getId());
                   wxUser1.setNickName(wxUser.getNickName());
                   wxUser1.setRealName(wxUser.getRealName());
                   wxUser1.setPhone(wxUser.getPhone());
                   wxUser1.setGender(wxUser.getGender());
                    wxUserService.updateWxUser(wxUser1);
                    codeService.deleteVerificationCodeByIds(verificationCodes.get(0).getId());
                    map = new HashMap();
                    map.put("status",1);
                }
            }
        } catch (Exception e) {
            map.put("status",0);
        }finally {
            return  map;
        }
    }
    /**
     * 更新地址
     * @param
     * @return
     */
    @GetMapping("/getCmInfo")
    @ResponseBody
    public CommunityManager getCmInfo( HttpServletRequest request) {
        Map map= new HashMap();

            String token = request.getHeader("token");
            String userId = JwtUtil.getUserId(token);
         CommunityManager communityManager = communityManagerService.selectCommunityManagerById(userId);
       if (communityManager!=null){
           communityManager.setPassword(null);
       }
        return communityManager;

    }


}
